// 引入数据库集合
const userModel = require('../../models/admin/userModel')
//jwt
const jwt = require('../../utils/JWT.js')
// 登录
const request = {
  login: (req, res) => {
    userModel.find({ ...req.body }, (err, data) => {
      if (data.length) {
        // 成功登录后在响应头给用户端返回token
        const token = jwt.generator(
          { id: data[0]._id, name: data[0].userName },
          '1d'
        )
        res.header('Authorization', token)
        res.send({ code: 200, message: '登陆成功', data })
      } else {
        res.send({ code: -1, message: '用户和密码不匹配' })
      }
    })
  },
  update: (req, res) => {
    const token = req.headers['authorization'].split(' ')[1]
    const payLoad = jwt.verify(token)
    console.log(payLoad)
    const { userName, introduction, gender } = req.body
    const avatar = `/avataruploads/${req.file.filename}`
    console.log(req.body)
    console.log(req.file)

    userModel.updateOne(
      { _id: payLoad.id },
      { userName, introduction, avatar, gender, file: req.file },
      (err, data) => {
        if (err) console.log(err)
      }
    )
    res.send('ok')
    // res.status(402).send({ message: '更新失败' })
  },
}

module.exports = request
